#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import json
import os
import sys
from typing import Any

# 全局变量，用于存储配置文件路径和最后修改时间戳
config_path = None
last_modified = 0
cached_config = {}
config_file_path = r"D:/code/gitee/cd_kunlun_assistant/data/app.json"


def __get_resource_path(relative_path) -> str:
    """获取资源文件的绝对路径"""
    # 检查打包后的目录中是否存在文件
    if getattr(sys, "frozen", False):
        return os.path.join(sys._MEIPASS, relative_path)  # type: ignore
    else:
        # 非打包情况下，使用相对路径
        return os.path.abspath(relative_path)


def __read_config() -> dict[str, Any]:
    """读取配置文件"""
    global config_path, last_modified, cached_config

    if config_path is None or not os.path.exists(config_path):
        config_path = __get_resource_path(config_file_path)
    # 检查文件是否有变化
    current_modified = os.path.getmtime(config_path)
    if current_modified != last_modified:
        last_modified = current_modified
        with open(config_path, "r", encoding="utf-8") as f:
            cached_config = json.load(f)
    return cached_config


def get_config(key: str) -> Any:
    """获取配置"""
    config = __read_config()
    if key in config.keys():
        return config.get(key, "")
    return None
